﻿using MyToDo.Service;
using MyToDo.Shared.Dtos;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.ViewModels
{
    public class ToDoViewModel : NavigationViewModel
    {
        public ToDoViewModel(IToDoService service, IContainerProvider provider) : base(provider)
		{
			ToDoDtos = new ObservableCollection<ToDoDto>();	
			AddCommand = new DelegateCommand(Add);
			SelectedCommand = new DelegateCommand<ToDoDto>(Selected);
			this.service = service;
           
        }

        private async  void Selected(ToDoDto obj)
        {
			var todoResult = await service.GetFirstOfDefaultAsync(obj.Id);
			if (todoResult != null)
			{
                if (todoResult.Status)
                {
                    CurrentDto = todoResult.Result;
                    IsRightDrawerOpen = true;
                }
            }
         
        }
		private ToDoDto currentDto;

		public ToDoDto CurrentDto
		{
			get { return currentDto; }
			set
			{
				currentDto = value;
				RaisePropertyChanged();
			}
		}

		private bool isRightDrawerOpen;

		public bool IsRightDrawerOpen
		{
			get { return isRightDrawerOpen; }
			set
			{
				isRightDrawerOpen = value;
				RaisePropertyChanged();
			}
		}

		private void Add()
        {
            IsRightDrawerOpen = true;
        }

        public DelegateCommand AddCommand { get; private set; }
        public DelegateCommand<ToDoDto> SelectedCommand { get; private set; }

        private readonly IToDoService service;
        private ObservableCollection<ToDoDto> toDoDtos;

		public ObservableCollection<ToDoDto> ToDoDtos
        {
			get { return toDoDtos; }
			set
			{
				toDoDtos = value;
				RaisePropertyChanged();
			}
		}

		async void GetDataAsync()
		{
			UpdateLoading(true);
			var todoResult = await service.GetAllAsync(new Shared.Parameters.QueryParameter()
			{
				PageIndex = 0,
				PageSize = 100,
				Search = "测试",
			}) ;

			if(todoResult.Status)
			{
				foreach(var item in todoResult.Result.Items)
				{
					ToDoDtos.Add(item);
				}
			}
            if (todoResult != null)
                UpdateLoading(false);
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="navigationContext"></param>
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            GetDataAsync();
        }
    }
}
